package com.ad2campaign.engine.core.schedulers;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.ad2campaign.engine.core.tasklet.TableScanningTask;

public class FixedIntervalSchedular implements GenericSchedular
{
	protected static final Logger LOGGER = Logger.getLogger(FixedIntervalSchedular.class); 
	private Timer timer = new  Timer("MessageTableScanner");
	private boolean started=false;
	private long initialDelay=5000;
	private long interval=5000;
	private TimerTask timerTask; 
	private boolean isMaster=false;
	
	public boolean isMaster() {
		return isMaster;
	}

	public void setMaster(boolean isMaster) {
		this.isMaster = isMaster;
	}

	public TimerTask getTimerTask() {
		return timerTask;
	}

	public void setTimerTask(TimerTask timerTask) {
		this.timerTask = timerTask;
	}

	public long getInitialDelay() {
		return initialDelay;
	}

	public void setInitialDelay(long initialDelay) {
		this.initialDelay = initialDelay;
	}

	public long getInterval() {
		return interval;
	}

	public void setInterval(long interval) {
		this.interval = interval;
	}

	@Override
	public void restart()
	{
		timer = new  Timer("MessageTableScanner");
		schedule();
 	}

	@Override
	public void start() 
	{
		if (!started &&  isMaster==true)
		{
 			schedule();
			started=true;
		}
		else
		{
			LOGGER.warn("Cannot start MessageTableScanner timer again.");
		}
	}

	private void schedule()
	{
		timer.scheduleAtFixedRate(timerTask, initialDelay, interval);
	}
	
	@Override
	public void stop() 
	{
		try 
		{
			timer.cancel();
		} catch (Exception e)
		{
			LOGGER.error("FixedIntervalSchedular.stop()"+e.getMessage());
			LOGGER.debug(e);
		}
	 	
		for (Thread thread :  threads )
		{
			try 
			{
				thread.join();
			}
			catch (Exception e) {}
		}
		try 
		{
	 		((TableScanningTask) timerTask).destroy();
		} catch (Exception e)
		{
			LOGGER.error("FixedIntervalSchedular.stop()"+e.getMessage());
			LOGGER.debug(e);
		}
	 			
	}

	
}
